package gw.com.android.ui;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.DiscussRequest;
import gw.com.android.ui.dialog.SharePopWindow;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.PackStatis;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.RecyclerClickListener;

/**
 * 带有点赞和分享的adapter
 */
public abstract class PraiseAndTransmitAdapter extends RecyclerView.Adapter {

    protected Activity mContext;
    private SharePopWindow mSharePopwindow;//分享功能弹层

    public PraiseAndTransmitAdapter(Activity context) {
        this.mContext = context;
    }

    //=====================分享相关的===============================
    public final static int EVENT_FROM_DISCUSS = 1;

    public final static int EVENT_FROM_ANALYST = 2;

    /**
     * 分享的点击监听
     */
    public class ShareClickListener implements View.OnClickListener {
        private String id;
        private String remark;
        private TextView tv_transmit_count;
        private int transmit_count;
        private int from;

        public ShareClickListener(String id, String remark, TextView tv_transmit_count, int transmit_count, int from) {
            this.id = id;
            this.remark = remark;
            this.tv_transmit_count = tv_transmit_count;
            this.transmit_count = transmit_count;
            this.from = from;
        }

        @Override
        public void onClick(View v) {
            String pointFrom;
            if (from == EVENT_FROM_DISCUSS) {//1，表示圈子里面过来的事件
                pointFrom = "clickSharePost1";
            } else// 其他，比如2，表示从分析师主页来的事件
                pointFrom = "clickSharePost2";
            PackStatis.getToService(pointFrom, PackStatis.EventCategory.CIRCLE.getValue(), null, null);
            showSharePopWindow(id, remark, tv_transmit_count, transmit_count);
        }
    }

    /**
     * 气泡提示
     */
    public void showToastPopWindow(String errorMessage) {
        new ToastPopWindow(mContext, errorMessage).show();
    }

    /**
     * 实现文本复制功能
     */
    public void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    private String makeTitle(String remark) {// 取remark前面20个字符，后面的全部用...
        StringBuilder title = new StringBuilder();
        if (remark.length() <= 20) {
            title.append(remark);
        } else {
            title.append(remark.substring(0, 20) + "...");
        }
        return title.toString();
    }

    String mTitle = "";
    String mId = "";
    TextView tv_transmit_count;
    int transmit_count;

    private static Map<String, Integer> transmitMap = new HashMap<>();//记录本地登录状态下，哪些帖子被转发了，下次登录的时候要清掉

    private void showSharePopWindow(String id, final String remark, final TextView tv_transmit_count_temp, int transmit_count_temp) {
        mTitle = makeTitle(remark);
        mId = id;
        tv_transmit_count = tv_transmit_count_temp;
        transmit_count = transmit_count_temp;
        if (null == mSharePopwindow) {
            //ShareSDK.initSDK(mContext);
            mSharePopwindow = new SharePopWindow((Activity) mContext, AppContances.SHARE_ADS_TYPE, null, null, new RecyclerClickListener() {
                @Override
                public void onClick(final int position, DataItemDetail itemDetail) {
                    Log.d("showSharePopWindowTag", mId + "-" + mTitle);//这里还真的不能用final关键字，因为 final 变量只能赋值一次。···会造成数据错误。
                    final String mUrl = "https://app.hx9999.com/gts2/share.html?id=" + mId;
                    transmitCommit(mId, tv_transmit_count, transmit_count);//后来改逻辑```-只要点了具体某个类型的分享，就进行分享数+1
                    Logger.e("分享详情连接：url == " + mUrl);
                    if (mSharePopwindow.getTitleId(position) == R.string.app_share_copy) {
                        copy(mUrl, mContext);
                        showToastPopWindow(AppMain.getAppString(R.string.app_share_copy_success));
                    } else {
                        mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position),
                                mTitle,
                                "我在富通环球投资发现一条神贴，速来围观>>",
                                mUrl, new PlatformActionListener() {
                                    @Override
                                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                                        showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
                                        // 分享成功之后应该要调用接口，来让后台知道 这条帖子被分享成功了
                                    }

                                    @Override
                                    public void onError(Platform platform, int i, Throwable throwable) {
//                                        showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + throwable.getMessage());
                                    }

                                    @Override
                                    public void onCancel(Platform platform, int i) {
//                                        showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
                                    }
                                });
                    }
                }
            });
        }
        mSharePopwindow.show();
    }

    //****************************adapter相关的网络请求之转发*******************************************
    private void transmitCommit(final String id, final TextView tv_transmit, final int transmit_count) {
        new DiscussRequest().transmit(id, new ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                if (DiscussRequest.COMMIT_SUCCESS.equals(result)) {
                    //这里要判断，当前传入的count是不是大于内存中的值，反正取较大的值，设置进去
                    Integer temp = transmitMap.get(id);
                    if (temp != null) {
                        if (temp > transmit_count) {
                            transmitMap.put(id, temp + 1);
                        } else {
                            transmitMap.put(id, transmit_count + 1);
                        }
                    } else
                        transmitMap.put(id, transmit_count + 1);

                    temp = transmitMap.get(id);
                    if (temp != null)
                        tv_transmit.setText(Integer.toString(temp));
                    else
                        tv_transmit.setText(transmit_count + 1);

                    Logger.d("transmitResult: 帖子id:" + id + "  转发已成功提交到服务器");
                } else {
                    Logger.d("transmitResult: 帖子id:" + id + "  转发提交到服务器失败...");
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                new ToastPopWindow(mContext, "服务器错误").show();
            }
        });
    }

    //=-===================点赞相关的==============================
    private final String localLikedIdsFileName = "discuss_like_ids_" + GTConfig.instance().mCurName + ".dat";
    protected List<String> likedIds;//点赞ID
    private final static int COLOR_PRAISED = 0xFFF74A18;
    private final static int COLOR_NOT_PRAISED = 0xFF999999;

    private static Map<String, Integer> likedMap = new HashMap<>();//记录本地登录状态下，哪些帖子被点赞了， 下次登录的时候要清掉

    public static void initLocalMap() {
        likedMap = new HashMap<>();
        transmitMap = new HashMap<>();
    }

    protected void initPraiseLayout(String id, ImageView mLikeIcon, TextView mPraiseBtn) {
        likedIds = getLikedIds();
        if (likedIds != null && likedIds.contains(id)) {
            mLikeIcon.setImageResource(R.mipmap.a_show_like_p);
            mPraiseBtn.setTextColor(COLOR_PRAISED);
        } else {
            mLikeIcon.setImageResource(R.mipmap.a_show_like);
            mPraiseBtn.setTextColor(COLOR_NOT_PRAISED);
        }
        Integer likedCount = likedMap.get(id);
        if (null != likedCount)
            mPraiseBtn.setText(getCountString(likedCount));
    }

    protected void initTransmitLayout(String id, int transmit_count, TextView mTransmitBtn) {
        Integer temp = transmitMap.get(id);
        if (null != temp) {
            int max = (transmit_count > temp ? transmit_count : temp);
            mTransmitBtn.setText(getCountString(max));
            transmitMap.put(id, max);
        }
    }

    /**
     * 获取本地缓存的点赞过的ID
     */
    protected List<String> getLikedIds() {
        String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        String value = CacheUtils.readFile(localLikedIdsFileName);
        if (!TextUtils.isEmpty(value)) {
            try {
                JSONObject json = new JSONObject(value);
                if (date.equals(json.optString("date"))) {
                    JSONArray idsJson = json.optJSONArray("ids");
                    if (idsJson != null && idsJson.length() > 0) {
                        List<String> list = new ArrayList<>();
                        for (int i = 0; i < idsJson.length(); i++) {
                            String id = idsJson.optString(i);
                            if (!TextUtils.isEmpty(id)) {
                                list.add(id);
                            }
                        }
                        return list;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected void addLikedId(String id) {
        if (likedIds == null) {
            likedIds = new ArrayList<>();
        }
        likedIds.add(id);
    }

    /**
     * 点赞过的ID 缓存到本地
     */
    protected void storeLikedId(String id) {
        if (TextUtils.isEmpty(id)) {
            return;
        }
        List<String> ids = getLikedIds();
        if (ids != null && ids.contains(id)) {
            return;
        }
        if (ids == null) {
            ids = new ArrayList<>();
        }
        ids.add(id);
        JSONObject json = new JSONObject();
        String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        try {
            json.put("date", date);
            json.put("ids", new JSONArray(ids));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CacheUtils.writeFile(localLikedIdsFileName, json.toString());
    }

    protected class PraiseLis implements View.OnClickListener {
        DiscussData mDiscussData;
        View mLikeEffect;
        TextView mPraiseBtn;
        ImageView mLikeIcon;

        public PraiseLis(DiscussData mDiscussData, View mLikeEffect, TextView mPraiseBtn, ImageView mLikeIcon) {
            this.mDiscussData = mDiscussData;
            this.mLikeEffect = mLikeEffect;
            this.mPraiseBtn = mPraiseBtn;
            this.mLikeIcon = mLikeIcon;
        }

        private boolean liking = false;

        @Override
        public void onClick(View v) {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
                new ToastPopWindow(mContext, AppMain.getAppString(R.string.home_discuss_praise)).show();
                return;
            }
            if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {//模拟用户不允许点赞
                new ToastPopWindow(mContext, AppMain.getAppString(R.string.home_discuss_not_real_3)).show();
                return;
            }
            if (liking || !NetworkMonitor.hasNetWork()) {
                return;
            }
            final DiscussData item = mDiscussData;
            if (item == null || TextUtils.isEmpty(item.id)) {
                return;
            }
            //startLikeEffect(mLikeIcon, false);

            if (mPraiseBtn.getCurrentTextColor() == COLOR_PRAISED) {//如果是已经点赞的状态，那么就弹出
                new ToastPopWindow(mContext, AppMain.getApp().getString(R.string.home_discuss_praise_repeat)).show();
                return;
            }

            final String id = item.id;
            if (likedIds != null && likedIds.contains(id)) {
                new ToastPopWindow(mContext, AppMain.getApp().getString(R.string.home_discuss_praise_repeat)).show();
                return;
            }
            liking = true;
            startLikeEffect(mLikeEffect, true);
            PackStatis.getToService("clickadmire", "circle", null, null);

            new DiscussRequest().like(id, new ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    addLikedId(id);

                    if (DiscussRequest.COMMIT_SUCCESS.equals(result)) {
                        item.praise++;
                        mPraiseBtn.setTextColor(0xFFF74A18);
                        dealCount(mPraiseBtn, item.praise);
                        mLikeIcon.setImageResource(R.mipmap.a_show_like_p);

                        //点赞成功
                        //用map记录一下当前点赞的这个帖子的id和最新点赞数,然后每次回到页面之后， 用这个map对所有数据进行弱刷新
                        likedMap.put(id, item.praise);

                    } else {
                        new ToastPopWindow(mContext, AppMain.getApp().getString(R.string.home_discuss_praise_repeat_2)).show();
                    }

                    storeLikedId(id);
                    liking = false;
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    new ToastPopWindow(mContext, "服务器错误").show();
                    liking = false;
                }
            });
        }
    }

    /**
     * 点赞动画
     */
    private void startLikeEffect(final View view, final boolean disappear) {
        view.setVisibility(View.VISIBLE);
        ValueAnimator scale = ValueAnimator.ofFloat(1, 1.15F, 1.3F, 1.45F, 1.5F, 1);
        scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (Float) animation.getAnimatedValue();
                view.setScaleX(value);
                view.setScaleY(value);
            }
        });
        scale.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (disappear) {
                    view.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        scale.setInterpolator(new OvershootInterpolator(1));
        scale.setDuration(1000);

        ValueAnimator rotate = ValueAnimator.ofInt(0, 30, 0);
        rotate.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                view.setRotation(value);
            }
        });
        rotate.setDuration(300);

        scale.start();
        rotate.start();
    }

    //============== 公共的===============

    /**
     * 执行数字显示规则
     */
    protected void dealCount(TextView tv_transmit_count, int count) {
        tv_transmit_count.setText(getCountString(count));
    }

    protected String getCountString(int count) {
        String res;
        if (count <= 0) {
            res = "";
        } else if (count <= 9999) {
            res = count + "";
        } else {
            double dd = count + 0.0d;
            DecimalFormat df = new DecimalFormat(".0");
            res = df.format(dd / 10000) + "万";
        }
        return res;
    }
}
